package vip.meeet.jdk.gc;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;

/**
 *
 强引用：普通的引用，强引用指向的对象不会被回收；
 软引用：仅有软引用指向的对象，只有发生gc且内存不足，才会被回收；
 弱引用：仅有弱引用指向的对象，只要发生gc就会被回收。
 */
public class RefStart {

    private static ThreadLocal<SimpleDateFormat> dateFormatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    public static void main(String[] args) {

        System.out.println(dateFormatter.get());
        dateFormatter = null;
        System.gc();
        System.out.println(dateFormatter.get());

//        two();
    }

    private static class Entry extends WeakReference<Object> {


        public Entry(Object referent) {
            super(referent);
        }

        public Entry(Object referent, ReferenceQueue<? super Object> q) {
            super(referent, q);
        }
    }

    private static void two(){
        Object a = new Object();
        Entry entry = new Entry(a);
        System.out.println(entry.get());
//        a = null;
        System.gc();
        System.out.println(entry.get());
    }

    private static void one(){
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();

        Object strongA = a;
        SoftReference<Object> softB = new SoftReference<>(b);
        WeakReference<Object> weakC = new WeakReference<>(c);


        a = null;
        b = null;
        c = null;

        System.out.println("Before gc...");
        System.out.println(String.format("strongA = %s, softB = %s, weakC = %s", strongA, softB.get(), weakC.get()));

        System.out.println("Run GC...");

        System.gc();

        System.out.println("After gc...");
        System.out.println(String.format("strongA = %s, softB = %s, weakC = %s", strongA, softB.get(), weakC.get()));

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}
